package com.sxm.yiwei.activitis;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.AccountAdapter;
import com.sxm.yiwei.beans.AcountListBeans;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class ChooseAliAcount extends BaseActivity implements View.OnClickListener{
    private String TAG ="choose";
    private ImageView back;
    private TextView addali;
    private SlideListView listview;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private AccountAdapter adapter;
    private Button choosebt;
    private Bundle bundle;

    @Override
    protected void onStart() {
        super.onStart();
        getAccountList();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_ali_acount);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid","");
        userId = sharedPreferences.getString("userId", "");
        token = sharedPreferences.getString("token", "");
        getAccountList();
        initChooseAliView();
    }

    private void getAccountList() {
        RequestParams params=  new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETOUTACCOUNTLIST);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("pageNo","1");
        object.put("pageSize","20");
        params.addBodyParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "onSuccess: 账户信息--"+result);
                getDataToList(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "onError: 账户列表--"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
        // 添加进listview
    private void getDataToList(String result) {
        JSONObject object = JSON.parseObject(result);
        JSONArray data = object.getJSONArray("data");
        final List<AcountListBeans.DataBean> acountlist = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            JSONObject obj = JSON.parseObject(String.valueOf(data.get(i)));
            String id = obj.getString("id");
            String isDefault = obj.getString("isDefault");
            String payeeAccount = obj.getString("payeeAccount");
            String realName = obj.getString("realName");
            AcountListBeans.DataBean dataBean = new AcountListBeans.DataBean();
            dataBean.setId(id);
            dataBean.setIsDefault(Integer.valueOf(isDefault));
            dataBean.setPayeeAccount(payeeAccount);
            dataBean.setRealName(realName);
            acountlist.add(dataBean);
        }
        adapter = new AccountAdapter(ChooseAliAcount.this,acountlist);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (AcountListBeans.DataBean dataBean:acountlist){
                    dataBean.setChecked(false);
                }
                acountlist.get(position).setChecked(true);
                AcountListBeans.DataBean dataBean = acountlist.get(position);

                if (dataBean.isChecked()){
                    String id1 = dataBean.getId();
                    String payeeAccount = dataBean.getPayeeAccount();
                    String realName = dataBean.getRealName();
                    bundle = new Bundle();
                    bundle.putString("id",id1);
                    bundle.putString("payeeAccount",payeeAccount);
                    bundle.putString("realName",realName);
                }else {}
                adapter.notifyDataSetChanged();
            }
        });
        adapter.setOnClickListenerEditOrDelete(new AccountAdapter.OnClickListenerEditOrDelete() {
            @Override
            public void OnClickListenerEdit(int position) {
                AcountListBeans.DataBean item = (AcountListBeans.DataBean) adapter.getItem(position);
               Intent intent = new Intent(ChooseAliAcount.this,AddALIAccount.class);
                intent.putExtra("from","bianji");
                intent.putExtra("id",item.getId());
                startActivity(intent);
                try {
                    listview.turnToNormal();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                listview.invalidate();
            }

            @Override
            public void OnClickListenerDelete(int position) {
                AcountListBeans.DataBean item = (AcountListBeans.DataBean) adapter.getItem(position);

                removeAccount(item.getId(),position);
            }
        });

    }
        //删除账户信息
    private void removeAccount(String id, final int position) {
        RequestParams params=  new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.REMOVEOUTACCOUNT);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("cashAccountId",id);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                JSONObject object1 = JSON.parseObject(result);
                String status = object1.getString("status");
                if (status.equals("1")){
                    adapter.acountlist.remove(position);
                    adapter.notifyDataSetChanged();
                    try {
                        listview.turnToNormal();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    listview.invalidate();
                }else {}
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initChooseAliView() {
        back = (ImageView) findViewById(R.id.chooseali_back);
        addali = (TextView) findViewById(R.id.choose_addali);
        listview = (SlideListView) findViewById(R.id.chooseali_listview);
        choosebt = (Button) findViewById(R.id.choose_bt);

        back.setOnClickListener(this);
        addali.setOnClickListener(this);
        choosebt.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.choose_addali:
                Intent intent = new Intent(ChooseAliAcount.this,AddALIAccount.class);
                intent.putExtra("from","tianjia");
                startActivity(intent);
                break;
            case R.id.chooseali_back:
                finish();
                break;
            case R.id.choose_bt:
                if (bundle==null){
                    Toast.makeText(this, "请选择提现账户", Toast.LENGTH_SHORT).show();
                }else {
                    Intent i = new Intent(ChooseAliAcount.this,MineAccountOutMoney.class);
                    i.putExtras(bundle);
                    ChooseAliAcount.this.setResult(RESULT_OK,i);
                    finish();
                }

                break;

        }
    }
}
